<template>
    <span class="xkl-text xkl-text-tree-select">{{ label }}</span>
</template>
<script setup lang="ts">
import { Ref, computed, onBeforeMount, ref } from 'vue';
import http from '~/utils/httpRequest';
import useApp from '@admin/_find/store/app';
import { toPromise } from '@xuekl/cli-utils';
defineOptions({ name: 'XklTextTreeSelect' })
const props = defineProps(['form', 'option'])
const list: Ref<any[]> = ref([])
const appStore = useApp()

const { form, option } = props
const config = option.config

const label = computed(() => {
    let labelText = ''
    const find = (vals) => {
        for (let item of vals) {
            if (item.value == form[option.prop]) {
                labelText = item.label
                break
            } else if (item.children) {
                find(item.children)
            }
        }
    }
    find(list.value)
    return labelText
})

const handleData = (data) => {
    data.forEach(inner => {
        inner.value = inner[config.valueTarget || 'value']
        inner.label = inner[config.labelTarget || 'label']
        if (inner.children) {
            handleData(inner.children)
        }
    })
    return data
}

onBeforeMount(() => {
    //先读取缓存中的数据
    if (appStore.urlSelectData[config.url]) {
        list.value = appStore.urlSelectData[config.url]
        // 如果缓存中没有数据，可能是以为接口已经发出数据未返回，需要等待
        if (!list.value.length) {
            toPromise(() => appStore.urlSelectData[config.url]).then((vals) => {
                list.value = vals
            })
        }
    } else {
        // 缓存中不存在再调用接口 并且开始在缓存中打标记，以防止一个页面有相同接口时会调用多次
        appStore.urlSelectData[config.url] = []
        http({
            url: http.adornUrl(config.url),
            method: 'get',
            params: http.adornParams({})
        }).then(({ data }) => {
            list.value = handleData(data.data)
            appStore.urlSelectData[config.url] = list.value
        })
    }
})

if (form._label) {
    form._label[option.prop] = label
} else {
    form._label = {
        [option.prop]: label
    }
}
</script>
<style lang="scss" scoped></style>